package com.wusiwei.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wusiwei.common.BusinessException;
import com.wusiwei.common.PageResult;
import com.wusiwei.common.Result;
import com.wusiwei.dto.MatchQueryDTO;
import com.wusiwei.entity.*;
import com.wusiwei.mapper.MatchMapper;
import com.wusiwei.service.*;
import com.wusiwei.vo.MatchField;
import com.wusiwei.vo.MatchResult;
import com.wusiwei.vo.MatchStatisticsData;
import com.wusiwei.vo.MatchedOrderVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 三单匹配服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MatchServiceImpl implements MatchService {
    private final OrderService orderService;
    private final ReceiptService receiptService;
    private final InvoiceService invoiceService;
    private final MatchMapper matchMapper;
    private final AIService aiService;

    /**
     * 新增三单匹配记录
     *
     * @param match 三单匹配对象
     * @return 操作结果
     */
    @Override
    @Transactional
    public Result<ThreeWayMatch> add(ThreeWayMatch match) {
        try {
            log.info("开始新增三单匹配记录, 订单ID: {}, 收货单ID: {}, 发票ID: {}",
                    match.getOrderId(), match.getReceiptId(), match.getInvoiceId());

            // 检查是否已存在相同的匹配记录
            ThreeWayMatch existMatch = matchMapper.findByDocumentIds(
                    match.getOrderId(), match.getReceiptId(), match.getInvoiceId());
            if (existMatch != null) {
                log.warn("已存在相同的三单匹配记录");
                return Result.error("已存在相同的三单匹配记录");
            }

            // 设置创建和更新时间
            match.setCreateTime(LocalDateTime.now());
            match.setUpdateTime(LocalDateTime.now());

            // 保存匹配记录
            matchMapper.insert(match);
            log.info("三单匹配记录保存成功, ID: {}", match.getId());

            return Result.success(match);
        } catch (Exception e) {
            log.error("新增三单匹配记录失败", e);
            return Result.error("新增三单匹配记录失败: " + e.getMessage());
        }
    }

    /**
     * 更新三单匹配记录
     *
     * @param match 三单匹配对象
     * @return 操作结果
     */
    @Override
    @Transactional
    public Result<ThreeWayMatch> update(ThreeWayMatch match) {
        try {
            // 检查匹配记录是否存在
            ThreeWayMatch existMatch = matchMapper.findById(match.getId());
            if (existMatch == null) {
                return Result.error("三单匹配记录不存在");
            }

            // 检查是否与其他记录冲突
            if (!existMatch.getOrderId().equals(match.getOrderId()) ||
                    !existMatch.getReceiptId().equals(match.getReceiptId()) ||
                    !existMatch.getInvoiceId().equals(match.getInvoiceId())) {
                ThreeWayMatch conflictMatch = matchMapper.findByDocumentIds(
                        match.getOrderId(), match.getReceiptId(), match.getInvoiceId());
                if (conflictMatch != null && !conflictMatch.getId().equals(match.getId())) {
                    return Result.error("已存在相同的三单匹配记录");
                }
            }

            // 设置更新时间
            match.setUpdateTime(LocalDateTime.now());

            // 更新匹配记录
            matchMapper.update(match);
            log.info("三单匹配记录更新成功, ID: {}", match.getId());

            return Result.success(match);
        } catch (Exception e) {
            log.error("更新三单匹配记录失败", e);
            return Result.error("更新三单匹配记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除三单匹配记录
     *
     * @param id 匹配记录ID
     * @return 操作结果
     */
    @Override
    @Transactional
    public Result<Void> delete(Long id) {
        try {
            // 检查匹配记录是否存在
            ThreeWayMatch match = matchMapper.findById(id);
            if (match == null) {
                return Result.error("三单匹配记录不存在");
            }

            // 删除匹配记录
            matchMapper.deleteById(id);
            log.info("三单匹配记录删除成功, ID: {}", id);

            return Result.success();
        } catch (Exception e) {
            log.error("删除三单匹配记录失败", e);
            return Result.error("删除三单匹配记录失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询三单匹配记录
     *
     * @param id 匹配记录ID
     * @return 三单匹配对象
     */
    @Override
    public Result<ThreeWayMatch> findById(Long id) {
        try {
            ThreeWayMatch match = matchMapper.findById(id);
            if (match == null) {
                return Result.error("三单匹配记录不存在");
            }
            return Result.success(match);
        } catch (Exception e) {
            log.error("查询三单匹配记录失败", e);
            return Result.error("查询三单匹配记录失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有三单匹配记录
     *
     * @return 三单匹配记录列表
     */
    @Override
    public Result<List<ThreeWayMatch>> findAll() {
        try {
            List<ThreeWayMatch> matches = matchMapper.findAll();
            return Result.success(matches);
        } catch (Exception e) {
            log.error("查询三单匹配记录列表失败", e);
            return Result.error("查询三单匹配记录列表失败: " + e.getMessage());
        }
    }

//    /**
//     * 根据条件查询三单匹配记录
//     *
//     * @param match 查询条件
//     * @return 三单匹配记录列表
//     */
//    @Override
//    public Result<List<ThreeWayMatch>> findByCondition(ThreeWayMatch match) {
//        try {
//            List<ThreeWayMatch> matches = matchMapper.findByCondition(match);
//            return Result.success(matches);
//        } catch (Exception e) {
//            log.error("根据条件查询三单匹配记录失败", e);
//            return Result.error("根据条件查询三单匹配记录失败: " + e.getMessage());
//        }
//    }
//
//    /**
//     * 根据条件Map查询三单匹配记录
//     *
//     * @param condition 查询条件Map
//     * @return 三单匹配记录列表
//     */
//    @Override
//    public List<ThreeWayMatch> findByConditionMap(Map<String, Object> condition) {
//        try {
//            log.info("根据条件Map查询三单匹配记录: {}", condition);
//
//            // 创建ThreeWayMatch对象
//            ThreeWayMatch match = new ThreeWayMatch();
//
//            // 设置查询条件
//            if (condition.containsKey("orderId")) {
//                match.setOrderId((Long) condition.get("orderId"));
//            }
//            if (condition.containsKey("receiptId")) {
//                match.setReceiptId((Long) condition.get("receiptId"));
//            }
//            if (condition.containsKey("invoiceId")) {
//                match.setInvoiceId((Long) condition.get("invoiceId"));
//            }
//            if (condition.containsKey("matchResult")) {
//                match.setMatchResult((String) condition.get("matchResult"));
//            }
//
//            // 查询匹配记录
//            log.info("转换后的ThreeWayMatch查询对象: {}", match);
//            List<ThreeWayMatch> matches = matchMapper.findByCondition(match);
//            log.info("查询结果数量: {}", matches.size());
//
//            return matches;
//        } catch (Exception e) {
//            log.error("根据条件Map查询三单匹配记录失败", e);
//            throw new RuntimeException("根据条件Map查询三单匹配记录失败: " + e.getMessage(), e);
//        }
//    }

//    /**
//     * 根据日期范围查询三单匹配记录
//     *
//     * @param startDate 开始日期
//     * @param endDate   结束日期
//     * @return 三单匹配记录列表
//     */
//    @Override
//    public Result<List<ThreeWayMatch>> findByDateRange(LocalDate startDate, LocalDate endDate) {
//        try {
//            // 参数校验
//            if (startDate == null || endDate == null) {
//                return Result.error("开始日期和结束日期不能为空");
//            }
//
//            if (startDate.isAfter(endDate)) {
//                return Result.error("开始日期不能大于结束日期");
//            }
//
//            List<ThreeWayMatch> matches = matchMapper.findByDateRange(startDate, endDate);
//            return Result.success(matches);
//        } catch (Exception e) {
//            log.error("日期范围查询三单匹配记录失败", e);
//            return Result.error("日期范围查询三单匹配记录失败: " + e.getMessage());
//        }
//    }

    /**
     * 执行三单匹配
     *
     * @param orderId   订单ID
     * @param receiptId 收货单ID
     * @param invoiceId 发票ID
     * @return 匹配结果
     */
    @Override
    @Transactional
    public MatchResult matchThreeDocuments(Long orderId, Long receiptId, Long invoiceId) {
        try {
            log.info("开始执行三单匹配, 订单ID: {}, 收货单ID: {}, 发票ID: {}", orderId, receiptId, invoiceId);

            // 获取三单数据
            Order order = orderService.getOrderById(orderId);
            Receipt receipt = receiptService.getReceiptById(receiptId);
            Invoice invoice = invoiceService.getById(invoiceId);

            if (order == null || receipt == null || invoice == null) {
                throw new BusinessException("找不到对应的订单、收货单或发票数据");
            }

            // 检查是否已存在匹配记录
            ThreeWayMatch existMatch = matchMapper.findByDocumentIds(
                    orderId, receiptId, invoiceId);
            if (existMatch != null) {
                log.warn("已存在相同的三单匹配记录");
                throw new BusinessException("已存在相同的三单匹配记录");
            }

            // 创建匹配结果对象
            MatchResult result = new MatchResult();
            result.setOrderInfo(order);
            result.setReceiptInfo(receipt);
            result.setInvoiceInfo(invoice);

            // 执行字段级匹配
            List<MatchField> fields = new ArrayList<>();
            boolean allMatch = true;

            // 匹配供应商
            String orderSupplier = order.getSupplierName() != null ? order.getSupplierName() : "";
            String receiptSupplier = receipt.getSupplierName() != null ? receipt.getSupplierName() : "";
            String invoiceSupplier = invoice.getSupplierName() != null ? invoice.getSupplierName() : "";

            boolean supplierMatch = orderSupplier.equals(receiptSupplier) && orderSupplier.equals(invoiceSupplier);
            allMatch = allMatch && supplierMatch;

            // 设置供应商名称
            result.setSupplierName(orderSupplier);

            // 添加供应商匹配字段
            MatchField supplierField = new MatchField();
            supplierField.setFieldName("供应商");
            supplierField.setOrderValue(orderSupplier);
            supplierField.setReceiptValue(receiptSupplier);
            supplierField.setInvoiceValue(invoiceSupplier);
            supplierField.setMatch(supplierMatch);
            fields.add(supplierField);

            // 匹配金额
            BigDecimal orderAmount = order.getTotalAmount();
            BigDecimal receiptAmount = receipt.getTotalAmount();
            BigDecimal invoiceAmount = invoice.getTotalAmount();

            // 使用0.01作为容差值进行比较
            BigDecimal tolerance = new BigDecimal("0.01");
            boolean amountMatch =
                    orderAmount.subtract(receiptAmount).abs().compareTo(tolerance) < 0 &&
                            orderAmount.subtract(invoiceAmount).abs().compareTo(tolerance) < 0;
            allMatch = allMatch && amountMatch;

            // 添加金额匹配字段
            MatchField amountField = new MatchField();
            amountField.setFieldName("金额");
            amountField.setOrderValue(orderAmount.toString());
            amountField.setReceiptValue(receiptAmount.toString());
            amountField.setInvoiceValue(invoiceAmount.toString());
            amountField.setMatch(amountMatch);
            fields.add(amountField);

            // 新增：优化匹配逻辑
            // 检查供应商和金额是否匹配
            boolean basicMatch = supplierMatch && amountMatch;

            if (!basicMatch) {
                log.info("供应商或金额不匹配，不进行进一步的明细匹配");
                // 如果供应商或金额不匹配，则直接设置明细不匹配
                MatchField detailsField = new MatchField();
                detailsField.setFieldName("明细");
                detailsField.setOrderValue(order.getItems() != null ? order.getItems().size() + "项" : "无明细");
                detailsField.setReceiptValue(receipt.getItems() != null ? receipt.getItems().size() + "项" : "无明细");
                detailsField.setInvoiceValue(invoice.getDetails() != null ? invoice.getDetails().size() + "项" : "无明细");
                detailsField.setMatch(false);
                fields.add(detailsField);

                allMatch = false;
            } else {
                // 只有供应商和金额匹配才进行明细匹配
                log.info("供应商和金额匹配成功，开始进行明细匹配");

                // 新增：匹配明细
                boolean detailsMatch = false;
                StringBuilder detailsInfo = new StringBuilder();

                // 获取订单明细、收货单明细和发票明细
                List<OrderItem> orderItems = order.getItems();
                List<ReceiptItem> receiptItems = receipt.getItems();
                List<InvoiceDetail> invoiceDetails = invoice.getDetails();

                // 检查明细是否为空
                if (orderItems == null || orderItems.isEmpty() ||
                        receiptItems == null || receiptItems.isEmpty() ||
                        invoiceDetails == null || invoiceDetails.isEmpty()) {
                    log.warn("订单、收货单或发票明细为空，无法进行明细匹配");
                    detailsMatch = false;
                    detailsInfo.append("明细数据不完整");
                } else {
                    // 提取明细名称进行比较
                    Set<String> orderItemNames = orderItems.stream()
                            .map(OrderItem::getItemName)
                            .collect(Collectors.toSet());

                    Set<String> receiptItemNames = receiptItems.stream()
                            .map(ReceiptItem::getItemName)
                            .collect(Collectors.toSet());

                    Set<String> invoiceItemNames = invoiceDetails.stream()
                            .map(InvoiceDetail::getItemName)
                            .collect(Collectors.toSet());

                    // 简单明细匹配：检查三单中的商品名称是否一致
                    boolean simpleMatch = orderItemNames.equals(receiptItemNames) && orderItemNames.equals(invoiceItemNames);

                    if (simpleMatch) {
                        detailsMatch = true;
                        detailsInfo.append("明细完全匹配");
                        log.info("明细完全匹配成功");
                    } else {
                        log.info("明细简单匹配失败，尝试使用AI进行兼容性判断");

                        // 根据不同情况使用AI进行兼容性判断
                        if (orderItemNames.equals(receiptItemNames) &&
                                (orderItemNames.size() < invoiceItemNames.size())) {

                            log.info("检测到可能的情况：订单和收货单是整体商品，发票是组件明细");

                            // 所有订单项
                            for (String orderItem : orderItemNames) {
                                // 调用AI服务判断该订单项是否可由发票明细组成
                                boolean compatible = aiService.checkItemsCompatibility(orderItem,
                                        new ArrayList<>(invoiceItemNames));

                                if (compatible) {
                                    detailsMatch = true;
                                    detailsInfo.append("AI判断明细兼容: ")
                                            .append(orderItem)
                                            .append(" 可由 ")
                                            .append(String.join(", ", invoiceItemNames))
                                            .append(" 组成");
                                    log.info("AI判断明细兼容成功：{} 可由 {} 组成",
                                            orderItem, String.join(", ", invoiceItemNames));
                                    break;  // 只要有一个订单项判断为兼容，就认为匹配成功
                                }
                            }

                        } else if (orderItemNames.equals(receiptItemNames) &&
                                (orderItemNames.size() > invoiceItemNames.size())) {

                            log.info("检测到可能的情况：订单和收货单是多个商品，发票是整体商品");

                            // 所有发票项
                            for (String invoiceItem : invoiceItemNames) {
                                // 调用AI服务判断该发票项是否可由订单明细组成
                                boolean compatible = aiService.checkItemsCompatibility(invoiceItem,
                                        new ArrayList<>(orderItemNames));

                                if (compatible) {
                                    detailsMatch = true;
                                    detailsInfo.append("AI判断明细兼容: ")
                                            .append(invoiceItem)
                                            .append(" 包含了 ")
                                            .append(String.join(", ", orderItemNames));
                                    log.info("AI判断明细兼容成功：{} 包含了 {}",
                                            invoiceItem, String.join(", ", orderItemNames));
                                    break;  // 只要有一个发票项判断为兼容，就认为匹配成功
                                }
                            }

                        } else {
                            log.info("订单、收货单和发票的商品明细不一致，尝试AI判断是否兼容");

                            // 如果订单和收货单一致，以订单为基准
                            if (orderItemNames.equals(receiptItemNames)) {
                                // 调用AI服务判断是否兼容
                                boolean compatible = false;

                                // 尝试双向判断：
                                // 1. 订单商品是否可以由发票商品组成
                                // 2. 发票商品是否可以由订单商品组成
                                compatible = checkBidirectionalCompatibility(
                                        new ArrayList<>(orderItemNames),
                                        new ArrayList<>(invoiceItemNames));

                                if (compatible) {
                                    detailsMatch = true;
                                    detailsInfo.append("AI判断明细兼容: 订单商品和发票商品互相兼容");
                                    log.info("AI判断明细互相兼容成功");
                                }
                            } else {
                                // 如果三者都不同，尝试所有可能的组合
                                log.info("三单明细各不相同，尝试所有可能的组合");

                                // 尝试每一种组合
                                boolean anyMatch = false;

                                // 尝试订单与发票
                                boolean orderInvoiceMatch = checkBidirectionalCompatibility(
                                        new ArrayList<>(orderItemNames),
                                        new ArrayList<>(invoiceItemNames));

                                if (orderInvoiceMatch) {
                                    anyMatch = true;
                                    detailsInfo.append("AI判断明细兼容: 订单商品和发票商品互相兼容; ");
                                    log.info("AI判断订单与发票明细兼容成功");
                                }

                                // 尝试收货单与发票
                                boolean receiptInvoiceMatch = checkBidirectionalCompatibility(
                                        new ArrayList<>(receiptItemNames),
                                        new ArrayList<>(invoiceItemNames));

                                if (receiptInvoiceMatch) {
                                    anyMatch = true;
                                    detailsInfo.append("AI判断明细兼容: 收货单商品和发票商品互相兼容; ");
                                    log.info("AI判断收货单与发票明细兼容成功");
                                }

                                detailsMatch = anyMatch;

                                if (!anyMatch) {
                                    log.info("所有AI兼容性判断均失败");
                                }
                            }
                        }

                        // 如果AI判断失败，记录明细不匹配信息
                        if (!detailsMatch) {
                            detailsInfo.append("明细不匹配，AI判断不兼容: ")
                                    .append("订单商品=").append(String.join(", ", orderItemNames))
                                    .append(", 收货单商品=").append(String.join(", ", receiptItemNames))
                                    .append(", 发票商品=").append(String.join(", ", invoiceItemNames));
                        }
                    }
                }

                // 添加明细匹配字段
                MatchField detailsField = new MatchField();
                detailsField.setFieldName("明细");
                detailsField.setOrderValue(orderItems != null ? orderItems.size() + "项" : "无明细");
                detailsField.setReceiptValue(receiptItems != null ? receiptItems.size() + "项" : "无明细");
                detailsField.setInvoiceValue(invoiceDetails != null ? invoiceDetails.size() + "项" : "无明细");
                detailsField.setMatch(detailsMatch);
                fields.add(detailsField);

                // 更新总体匹配结果
                allMatch = allMatch && detailsMatch;

                // 记录差异信息（只在明细不匹配时添加）
                if (!detailsMatch) {
                    log.info("明细匹配失败，详细信息: {}", detailsInfo.toString());
                }
            }

            // 创建三单匹配记录
            ThreeWayMatch match = new ThreeWayMatch();
            match.setOrderId(orderId);
            match.setReceiptId(receiptId);
            match.setInvoiceId(invoiceId);
            match.setOrderNumber(order.getOrderNumber());
            match.setReceiptNumber(receipt.getReceiptNumber());
            match.setInvoiceNumber(invoice.getInvoiceNumber());
            match.setSupplierName(orderSupplier);
            match.setOrderAmount(orderAmount);
            match.setReceiptAmount(receiptAmount);
            match.setInvoiceAmount(invoiceAmount);
            match.setMatchResult(allMatch ? "匹配" : "不匹配");

            // 记录差异信息
            StringBuilder difference = new StringBuilder();
            for (MatchField field : fields) {
                if (!field.isMatch()) {
                    difference.append(field.getFieldName()).append("不一致: ");
                    difference.append("订单=").append(field.getOrderValue()).append(", ");
                    difference.append("收货单=").append(field.getReceiptValue()).append(", ");
                    difference.append("发票=").append(field.getInvoiceValue()).append("; ");
                }
            }
            match.setDifference(difference.toString());

            // 设置时间
            LocalDateTime now = LocalDateTime.now();
            match.setCreateTime(now);
            match.setUpdateTime(now);
            match.setMatchTime(now);

            // 保存匹配记录
            matchMapper.insert(match);
            log.info("三单匹配完成, 结果: {}", match.getMatchResult());

            // 如果匹配成功，则更新发票表中的订单ID和收货单ID
            if (allMatch) {
                log.info("三单匹配成功，更新发票关联信息，发票ID: {}, 订单ID: {}, 收货单ID: {}",
                        invoice.getId(), order.getId(), receipt.getId());

                // 设置发票的订单ID和收货单ID
                Invoice invoiceToUpdate = new Invoice();
                invoiceToUpdate.setId(invoice.getId());
                invoiceToUpdate.setOrderId(order.getId());
                invoiceToUpdate.setReceiptId(receipt.getId());

                // 更新发票信息
                invoiceService.update(invoiceToUpdate);
                log.info("发票关联信息更新成功");
            } else {
                log.info("三单匹配不成功，不更新发票关联信息");
            }

            // 在返回结果中添加单号和时间信息
            result.setOrderNumber(order.getOrderNumber());
            result.setReceiptNumber(receipt.getReceiptNumber());
            result.setInvoiceNumber(invoice.getInvoiceNumber());
            result.setMatchTime(LocalDateTime.now());
            result.setMatch(allMatch);
            result.setFields(fields);

            log.info("三单匹配完成：订单编号={}, 收货单编号={}, 发票编号={}, 匹配结果={}, 匹配时间={}",
                    order.getOrderNumber(), receipt.getReceiptNumber(), invoice.getInvoiceNumber(),
                    allMatch ? "匹配" : "不匹配", LocalDateTime.now());

            return result;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("三单匹配失败", e);
            throw new BusinessException("三单匹配执行失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取匹配统计信息
     *
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getMatchStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        try {
            // 创建MatchStatisticsData对象
            MatchStatisticsData data = new MatchStatisticsData();

            // 设置概览数据
            Map<String, Object> overview = new HashMap<>();
            int totalCount = matchMapper.countTotal();
            overview.put("totalMatches", totalCount);

            // 获取匹配结果统计
            List<Map<String, Object>> resultStats = matchMapper.countByMatchResult();
            int successMatches = 0;
            int partialMatches = 0;
            int pendingMatches = 0;
            int exceptionMatches = 0;

            for (Map<String, Object> stat : resultStats) {
                String matchResult = (String) stat.get("matchResult");
                int count = ((Number) stat.get("count")).intValue();

                if ("匹配".equals(matchResult)) {
                    successMatches = count;
                } else if ("部分匹配".equals(matchResult)) {
                    partialMatches = count;
                } else if ("待匹配".equals(matchResult)) {
                    pendingMatches = count;
                } else if ("不匹配".equals(matchResult)) {
                    exceptionMatches = count;
                }
            }

            overview.put("successMatches", successMatches);
            overview.put("partialMatches", partialMatches);
            overview.put("pendingMatches", pendingMatches);
            overview.put("exceptionMatches", exceptionMatches);

            // 计算成功率
            String successRate = totalCount > 0 ? String.format("%.1f%%", ((double) successMatches / totalCount) * 100) : "0%";
            overview.put("successRate", successRate);

            data.setOverview(overview);

            // 设置状态分布
            data.setStatusDistribution(resultStats);

            // 设置月度趋势
            data.setMonthlyTrend(matchMapper.countMatchTrendByMonth());

            // 将数据转换为Map返回
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(data);
            statistics = objectMapper.readValue(jsonString, Map.class);

            return statistics;
        } catch (Exception e) {
            log.error("获取匹配统计信息失败", e);
            return statistics;
        }
    }

//    /**
//     * 分页查询三单匹配记录
//     *
//     * @param pageRequest 分页请求
//     * @return 分页结果
//     */
//    @Override
//    public PageResult<ThreeWayMatch> page(PageRequest pageRequest) {
//        try {
//            // 构建查询参数
//            Map<String, Object> params = new HashMap<>();
//            params.put("pageNum", pageRequest.getPageNum());
//            params.put("pageSize", pageRequest.getPageSize());
//
//            // 设置排序
//            if (pageRequest.getOrderBy() != null && !pageRequest.getOrderBy().isEmpty()) {
//                params.put("orderBy", pageRequest.getOrderBy());
//                params.put("orderDirection", pageRequest.getOrderDirection());
//            }
//
//            // 查询总数
//            Long total = Long.valueOf(matchMapper.countTotal());
//
//            // 计算偏移量
//            int offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();
//            params.put("offset", offset);
//
//            // 分页查询
//            List<ThreeWayMatch> matches = matchMapper.findByPage(params);
//
//            return PageResult.of(total, matches, pageRequest.getPageSize(), pageRequest.getPageNum());
//        } catch (Exception e) {
//            log.error("分页查询三单匹配记录失败", e);
//            throw new BusinessException("分页查询三单匹配记录失败: " + e.getMessage());
//        }
//    }
//
//    /**
//     * 按日期统计三单匹配记录
//     *
//     * @param startDate 开始日期
//     * @param endDate   结束日期
//     * @return 日期统计结果
//     */
//    @Override
//    public List<Map<String, Object>> getMatchDateStats(String startDate, String endDate) {
//        log.info("获取三单匹配日期统计, 日期范围: {} - {}", startDate, endDate);
//        try {
//            // 转换日期格式
//            LocalDate start = null;
//            LocalDate end = null;
//
//            if (startDate != null && !startDate.isEmpty()) {
//                start = LocalDate.parse(startDate);
//            }
//
//            if (endDate != null && !endDate.isEmpty()) {
//                end = LocalDate.parse(endDate);
//            }
//
//            // 查询指定日期范围的匹配记录
//            List<ThreeWayMatch> matches = matchMapper.findByDateRange(start, end);
//
//            // 按日期分组统计
//            Map<String, List<ThreeWayMatch>> groupedByDate = matches.stream()
//                    .collect(Collectors.groupingBy(
//                            match -> match.getCreateTime().toLocalDate().toString()
//                    ));
//
//            // 构建统计结果
//            List<Map<String, Object>> result = new ArrayList<>();
//
//            groupedByDate.forEach((date, matchList) -> {
//                Map<String, Object> dateStats = new HashMap<>();
//                dateStats.put("date", date);
//                dateStats.put("totalCount", matchList.size());
//
//                // 统计匹配和不匹配的数量
//                long matchCount = matchList.stream()
//                        .filter(match -> "匹配".equals(match.getMatchResult()))
//                        .count();
//                long mismatchCount = matchList.size() - matchCount;
//
//                dateStats.put("matchCount", matchCount);
//                dateStats.put("mismatchCount", mismatchCount);
//
//                // 计算匹配率
//                double matchRate = matchList.isEmpty() ? 0.0 :
//                        (double) matchCount / matchList.size() * 100;
//                dateStats.put("matchRate", matchRate);
//
//                result.add(dateStats);
//            });
//
//            // 按日期排序
//            result.sort(Comparator.comparing(item -> (String) item.get("date")));
//
//            return result;
//        } catch (Exception e) {
//            log.error("获取三单匹配日期统计失败", e);
//            throw new RuntimeException("获取三单匹配日期统计失败: " + e.getMessage());
//        }
//    }

    /**
     * 分页查询匹配记录
     *
     * @param pageNum      页码
     * @param pageSize     每页大小
     * @param supplierName 供应商名称
     * @param matchResult  匹配结果
     * @param startDate    开始日期
     * @param endDate      结束日期
     * @return 匹配记录分页结果
     */
    @Override
    public Object getMatchPage(int pageNum, int pageSize, String supplierName,
                               String matchResult, String startDate, String endDate) {
        try {
            // 验证分页参数
            if (pageNum <= 0) {
                pageNum = 1;
                log.warn("页码参数无效，已设置为默认值1");
            }

            if (pageSize <= 0 || pageSize > 100) {
                pageSize = 10;
                log.warn("每页大小参数无效，已设置为默认值10");
            }

            // 计算分页偏移量
            int offset = (pageNum - 1) * pageSize;

            // 转换日期格式
            Date startDateTime = null;
            Date endDateTime = null;
            try {
                if (startDate != null && !startDate.isEmpty()) {
                    startDateTime = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
                }
                if (endDate != null && !endDate.isEmpty()) {
                    endDateTime = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
                }
            } catch (Exception e) {
                log.error("日期格式转换错误", e);
                throw new BusinessException("日期格式不正确，应为yyyy-MM-dd");
            }

            // 查询数据
            List<ThreeWayMatch> matches = matchMapper.findByPage(supplierName, matchResult,
                    startDateTime, endDateTime, offset, pageSize);

            // 统计总记录数
            int total = matchMapper.count(supplierName, matchResult, startDateTime, endDateTime);

            // 构造分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("records", matches);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);

            return result;
        } catch (Exception e) {
            log.error("分页查询匹配记录失败", e);
            throw new BusinessException("分页查询匹配记录失败: " + e.getMessage());
        }
    }

    /**
     * 导出匹配记录
     *
     * @param supplierName 供应商名称
     * @param matchResult  匹配结果
     * @param startDate    开始日期
     * @param endDate      结束日期
     * @return 导出的文件二进制数据
     */
    @Override
    public byte[] exportMatches(String supplierName, String matchResult,
                                String startDate, String endDate) {
        try {
            log.info("开始导出匹配记录, 供应商: {}, 匹配结果: {}, 日期范围: {} - {}",
                    supplierName, matchResult, startDate, endDate);

            // 转换日期格式
            Date startDateTime = null;
            Date endDateTime = null;
            try {
                if (startDate != null && !startDate.isEmpty()) {
                    startDateTime = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
                }
                if (endDate != null && !endDate.isEmpty()) {
                    endDateTime = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
                }
            } catch (Exception e) {
                log.error("日期格式转换错误", e);
                throw new BusinessException("日期格式不正确，应为yyyy-MM-dd");
            }

            // 获取数据
            List<ThreeWayMatch> matches = matchMapper.findByPage(supplierName, matchResult,
                    startDateTime, endDateTime, 0, Integer.MAX_VALUE);

            log.info("查询到{}条匹配记录", matches.size());

            if (matches.isEmpty()) {
                log.warn("没有匹配记录数据可导出");
                return new byte[0];
            }

            // 创建工作簿 - 使用SXSSFWorkbook提高性能并确保兼容性
            SXSSFWorkbook workbook = new SXSSFWorkbook();
            SXSSFSheet sheet = workbook.createSheet("匹配记录");
            // 设置自动刷新，避免大数据量时内存溢出
            workbook.setCompressTempFiles(true);
            // 启用列跟踪，以便能够自动调整列宽
            // 由于SXSSFWorkbook不支持trackAllColumns方法，需要单独跟踪每一列
            // 创建一个循环来跟踪所有需要自动调整大小的列
            for (int i = 0; i < 12; i++) { // 假设有12列需要自动调整宽度
                sheet.trackColumnForAutoSizing(i);
            }

            // 创建标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);

            // 创建数据样式
            CellStyle dataStyle = workbook.createCellStyle();
            dataStyle.setBorderTop(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);

            // 创建金额样式
            CellStyle amountStyle = workbook.createCellStyle();
            amountStyle.cloneStyleFrom(dataStyle);
            DataFormat format = workbook.createDataFormat();
            amountStyle.setDataFormat(format.getFormat("#,##0.00"));

            // 创建日期样式
            CellStyle dateStyle = workbook.createCellStyle();
            dateStyle.cloneStyleFrom(dataStyle);
            CreationHelper createHelper = workbook.getCreationHelper();
            // 使用正确的日期格式模式：yyyy-MM-dd HH:mm:ss (注意MM是月份，mm是分钟，HH是24小时制)
            dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {
                    "ID", "订单号", "收货单号", "发票号", "供应商", "订单金额", "收货单金额",
                    "发票金额", "匹配结果", "差异说明", "匹配时间", "创建时间"
            };

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < matches.size(); i++) {
                ThreeWayMatch match = matches.get(i);
                Row row = sheet.createRow(i + 1);

                // ID
                Cell idCell = row.createCell(0);
                idCell.setCellValue(match.getId());
                idCell.setCellStyle(dataStyle);

                // 订单号
                Cell orderNumberCell = row.createCell(1);
                orderNumberCell.setCellValue(match.getOrderNumber());
                orderNumberCell.setCellStyle(dataStyle);

                // 收货单号
                Cell receiptNumberCell = row.createCell(2);
                receiptNumberCell.setCellValue(match.getReceiptNumber());
                receiptNumberCell.setCellStyle(dataStyle);

                // 发票号
                Cell invoiceNumberCell = row.createCell(3);
                invoiceNumberCell.setCellValue(match.getInvoiceNumber());
                invoiceNumberCell.setCellStyle(dataStyle);

                // 供应商
                Cell supplierCell = row.createCell(4);
                supplierCell.setCellValue(match.getSupplierName());
                supplierCell.setCellStyle(dataStyle);

                // 订单金额
                Cell orderAmountCell = row.createCell(5);
                if (match.getOrderAmount() != null) {
                    orderAmountCell.setCellValue(match.getOrderAmount().doubleValue());
                    orderAmountCell.setCellStyle(amountStyle);
                } else {
                    orderAmountCell.setCellValue(0.00);
                    orderAmountCell.setCellStyle(amountStyle);
                }

                // 收货单金额
                Cell receiptAmountCell = row.createCell(6);
                if (match.getReceiptAmount() != null) {
                    receiptAmountCell.setCellValue(match.getReceiptAmount().doubleValue());
                    receiptAmountCell.setCellStyle(amountStyle);
                } else {
                    receiptAmountCell.setCellValue(0.00);
                    receiptAmountCell.setCellStyle(amountStyle);
                }

                // 发票金额
                Cell invoiceAmountCell = row.createCell(7);
                if (match.getInvoiceAmount() != null) {
                    invoiceAmountCell.setCellValue(match.getInvoiceAmount().doubleValue());
                    invoiceAmountCell.setCellStyle(amountStyle);
                } else {
                    invoiceAmountCell.setCellValue(0.00);
                    invoiceAmountCell.setCellStyle(amountStyle);
                }

                // 匹配结果
                Cell resultCell = row.createCell(8);
                resultCell.setCellValue(match.getMatchResult());
                resultCell.setCellStyle(dataStyle);

                // 差异说明
                Cell differenceCell = row.createCell(9);
                differenceCell.setCellValue(match.getDifference());
                differenceCell.setCellStyle(dataStyle);

                // 匹配时间
                Cell matchTimeCell = row.createCell(10);
                if (match.getMatchTime() != null) {
                    matchTimeCell.setCellValue(Date.from(match.getMatchTime().atZone(java.time.ZoneId.systemDefault()).toInstant()));
                    matchTimeCell.setCellStyle(dateStyle);
                } else {
                    matchTimeCell.setCellStyle(dataStyle);
                }

                // 创建时间
                Cell createTimeCell = row.createCell(11);
                if (match.getCreateTime() != null) {
                    createTimeCell.setCellValue(Date.from(match.getCreateTime().atZone(java.time.ZoneId.systemDefault()).toInstant()));
                    createTimeCell.setCellStyle(dateStyle);
                } else {
                    createTimeCell.setCellStyle(dataStyle);
                }
            }

            // 调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
                // 为了美观，稍微增加一点列宽
                int currentWidth = sheet.getColumnWidth(i);
                sheet.setColumnWidth(i, currentWidth + 500);
            }

            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                workbook.write(outputStream);
                byte[] fileContent = outputStream.toByteArray();
                log.info("成功生成Excel文件，大小: {} 字节", fileContent.length);
                return fileContent;
            } finally {
                // 确保资源被正确释放
                outputStream.close();
                workbook.close();
                // 如果使用的是SXSSFWorkbook，需要调用dispose方法删除临时文件
                if (workbook instanceof SXSSFWorkbook) {
                    ((SXSSFWorkbook) workbook).dispose();
                }
            }
        } catch (Exception e) {
            log.error("导出匹配记录失败: {}", e.getMessage(), e);
            throw new BusinessException("导出匹配记录失败: " + e.getMessage());
        }
    }

//    /**
//     * 实现match方法，复用matchThreeDocuments逻辑
//     *
//     * @param order   订单对象
//     * @param receipt 收货单对象
//     * @param invoice 发票对象
//     * @return 匹配结果
//     */
//    @Override
//    @Transactional
//    public Result<ThreeWayMatch> match(Order order, Receipt receipt, Invoice invoice) {
//        try {
//            log.info("开始执行单据匹配, 订单编号: {}, 收货单编号: {}, 发票编号: {}",
//                    order.getOrderNumber(), receipt.getReceiptNumber(), invoice.getInvoiceNumber());
//
//            // 检查参数
//            if (order == null || receipt == null || invoice == null) {
//                throw new BusinessException("订单、收货单或发票不能为空");
//            }
//
//            // 检查是否已存在匹配记录
//            ThreeWayMatch existMatch = matchMapper.findByDocumentIds(
//                    order.getId(), receipt.getId(), invoice.getId());
//            if (existMatch != null) {
//                log.warn("已存在相同的三单匹配记录");
//                return Result.error("已存在相同的三单匹配记录");
//            }
//
//            // 创建三单匹配记录
//            ThreeWayMatch match = new ThreeWayMatch();
//            match.setOrderId(order.getId());
//            match.setReceiptId(receipt.getId());
//            match.setInvoiceId(invoice.getId());
//            match.setOrderNumber(order.getOrderNumber());
//            match.setReceiptNumber(receipt.getReceiptNumber());
//            match.setInvoiceNumber(invoice.getInvoiceNumber());
//
//            // 创建差异信息
//            StringBuilder difference = new StringBuilder();
//            boolean allMatch = true;
//
//            // 匹配供应商
//            String orderSupplier = order.getSupplierName() != null ? order.getSupplierName() : "";
//            String receiptSupplier = receipt.getSupplierName() != null ? receipt.getSupplierName() : "";
//            String invoiceSupplier = invoice.getSupplierName() != null ? invoice.getSupplierName() : "";
//
//            boolean supplierMatch = orderSupplier.equals(receiptSupplier) && orderSupplier.equals(invoiceSupplier);
//            allMatch = allMatch && supplierMatch;
//            match.setSupplierName(orderSupplier);
//
//            if (!supplierMatch) {
//                difference.append("供应商名称不一致: ");
//                difference.append("订单=").append(orderSupplier).append(", ");
//                difference.append("收货单=").append(receiptSupplier).append(", ");
//                difference.append("发票=").append(invoiceSupplier).append("; ");
//            }
//
//            // 匹配总金额
//            BigDecimal orderAmount = order.getTotalAmount() != null ? order.getTotalAmount() : BigDecimal.ZERO;
//            BigDecimal receiptAmount = receipt.getTotalAmount() != null ? receipt.getTotalAmount() : BigDecimal.ZERO;
//            BigDecimal invoiceAmount = invoice.getTotalAmount() != null ? invoice.getTotalAmount() : BigDecimal.ZERO;
//
//            match.setOrderAmount(orderAmount);
//            match.setReceiptAmount(receiptAmount);
//            match.setInvoiceAmount(invoiceAmount);
//
//            // 使用0.01作为容差值进行比较
//            BigDecimal tolerance = new BigDecimal("0.01");
//            boolean amountMatch =
//                    orderAmount.subtract(receiptAmount).abs().compareTo(tolerance) < 0 &&
//                            orderAmount.subtract(invoiceAmount).abs().compareTo(tolerance) < 0;
//            allMatch = allMatch && amountMatch;
//
//            if (!amountMatch) {
//                difference.append("金额不一致: ");
//                difference.append("订单=").append(orderAmount).append(", ");
//                difference.append("收货单=").append(receiptAmount).append(", ");
//                difference.append("发票=").append(invoiceAmount).append("; ");
//            }
//
//            // 优化匹配逻辑：只有供应商和金额都匹配才进行明细匹配
//            boolean basicMatch = supplierMatch && amountMatch;
//
//            if (!basicMatch) {
//                log.info("供应商或金额不匹配，不进行进一步的明细匹配");
//                // 不需要设置detailsMatch，直接使用allMatch（此时已经是false）
//                match.setMatchResult("不匹配");
//            } else {
//                log.info("供应商和金额匹配成功，开始进行明细匹配");
//
//                // 明细匹配
//                boolean detailsMatch = false;
//                StringBuilder detailsInfo = new StringBuilder();
//
//                // 获取订单明细、收货单明细和发票明细
//                List<OrderItem> orderItems = order.getItems();
//                List<ReceiptItem> receiptItems = receipt.getItems();
//                List<InvoiceDetail> invoiceDetails = invoice.getDetails();
//
//                // 检查明细是否为空
//                if (orderItems == null || orderItems.isEmpty() ||
//                        receiptItems == null || receiptItems.isEmpty() ||
//                        invoiceDetails == null || invoiceDetails.isEmpty()) {
//                    log.warn("订单、收货单或发票明细为空，无法进行明细匹配");
//                    detailsMatch = false;
//                    detailsInfo.append("明细数据不完整");
//                } else {
//                    // 提取明细名称进行比较
//                    Set<String> orderItemNames = orderItems.stream()
//                            .map(OrderItem::getItemName)
//                            .collect(Collectors.toSet());
//
//                    Set<String> receiptItemNames = receiptItems.stream()
//                            .map(ReceiptItem::getItemName)
//                            .collect(Collectors.toSet());
//
//                    Set<String> invoiceItemNames = invoiceDetails.stream()
//                            .map(InvoiceDetail::getItemName)
//                            .collect(Collectors.toSet());
//
//                    // 简单明细匹配：检查三单中的商品名称是否一致
//                    boolean simpleMatch = orderItemNames.equals(receiptItemNames) && orderItemNames.equals(invoiceItemNames);
//
//                    if (simpleMatch) {
//                        detailsMatch = true;
//                        detailsInfo.append("明细完全匹配");
//                        log.info("明细完全匹配成功");
//                    } else {
//                        log.info("明细简单匹配失败，尝试使用AI进行兼容性判断");
//
//                        // 根据不同情况使用AI进行兼容性判断
//                        if (orderItemNames.equals(receiptItemNames) &&
//                                (orderItemNames.size() < invoiceItemNames.size())) {
//
//                            log.info("检测到可能的情况：订单和收货单是整体商品，发票是组件明细");
//
//                            // 所有订单项
//                            for (String orderItem : orderItemNames) {
//                                // 调用AI服务判断该订单项是否可由发票明细组成
//                                boolean compatible = aiService.checkItemsCompatibility(orderItem,
//                                        new ArrayList<>(invoiceItemNames));
//
//                                if (compatible) {
//                                    detailsMatch = true;
//                                    detailsInfo.append("AI判断明细兼容: ")
//                                            .append(orderItem)
//                                            .append(" 可由 ")
//                                            .append(String.join(", ", invoiceItemNames))
//                                            .append(" 组成");
//                                    log.info("AI判断明细兼容成功：{} 可由 {} 组成",
//                                            orderItem, String.join(", ", invoiceItemNames));
//                                    break;  // 只要有一个订单项判断为兼容，就认为匹配成功
//                                }
//                            }
//
//                        } else if (orderItemNames.equals(receiptItemNames) &&
//                                (orderItemNames.size() > invoiceItemNames.size())) {
//
//                            log.info("检测到可能的情况：订单和收货单是多个商品，发票是整体商品");
//
//                            // 所有发票项
//                            for (String invoiceItem : invoiceItemNames) {
//                                // 调用AI服务判断该发票项是否可由订单明细组成
//                                boolean compatible = aiService.checkItemsCompatibility(invoiceItem,
//                                        new ArrayList<>(orderItemNames));
//
//                                if (compatible) {
//                                    detailsMatch = true;
//                                    detailsInfo.append("AI判断明细兼容: ")
//                                            .append(invoiceItem)
//                                            .append(" 包含了 ")
//                                            .append(String.join(", ", orderItemNames));
//                                    log.info("AI判断明细兼容成功：{} 包含了 {}",
//                                            invoiceItem, String.join(", ", orderItemNames));
//                                    break;  // 只要有一个发票项判断为兼容，就认为匹配成功
//                                }
//                            }
//
//                        } else {
//                            log.info("订单、收货单和发票的商品明细不一致，尝试AI判断是否兼容");
//
//                            // 如果订单和收货单一致，以订单为基准
//                            if (orderItemNames.equals(receiptItemNames)) {
//                                // 调用AI服务判断是否兼容
//                                boolean compatible = false;
//
//                                // 尝试双向判断：
//                                // 1. 订单商品是否可以由发票商品组成
//                                // 2. 发票商品是否可以由订单商品组成
//                                compatible = checkBidirectionalCompatibility(
//                                        new ArrayList<>(orderItemNames),
//                                        new ArrayList<>(invoiceItemNames));
//
//                                if (compatible) {
//                                    detailsMatch = true;
//                                    detailsInfo.append("AI判断明细兼容: 订单商品和发票商品互相兼容");
//                                    log.info("AI判断明细互相兼容成功");
//                                }
//                            } else {
//                                // 如果三者都不同，尝试所有可能的组合
//                                log.info("三单明细各不相同，尝试所有可能的组合");
//
//                                // 尝试每一种组合
//                                boolean anyMatch = false;
//
//                                // 尝试订单与发票
//                                boolean orderInvoiceMatch = checkBidirectionalCompatibility(
//                                        new ArrayList<>(orderItemNames),
//                                        new ArrayList<>(invoiceItemNames));
//
//                                if (orderInvoiceMatch) {
//                                    anyMatch = true;
//                                    detailsInfo.append("AI判断明细兼容: 订单商品和发票商品互相兼容; ");
//                                    log.info("AI判断订单与发票明细兼容成功");
//                                }
//
//                                // 尝试收货单与发票
//                                boolean receiptInvoiceMatch = checkBidirectionalCompatibility(
//                                        new ArrayList<>(receiptItemNames),
//                                        new ArrayList<>(invoiceItemNames));
//
//                                if (receiptInvoiceMatch) {
//                                    anyMatch = true;
//                                    detailsInfo.append("AI判断明细兼容: 收货单商品和发票商品互相兼容; ");
//                                    log.info("AI判断收货单与发票明细兼容成功");
//                                }
//
//                                detailsMatch = anyMatch;
//
//                                if (!anyMatch) {
//                                    log.info("所有AI兼容性判断均失败");
//                                }
//                            }
//                        }
//
//                        // 如果AI判断失败，记录明细不匹配信息
//                        if (!detailsMatch) {
//                            detailsInfo.append("明细不匹配，AI判断不兼容: ")
//                                    .append("订单商品=").append(String.join(", ", orderItemNames))
//                                    .append(", 收货单商品=").append(String.join(", ", receiptItemNames))
//                                    .append(", 发票商品=").append(String.join(", ", invoiceItemNames));
//                        }
//                    }
//                }
//
//                // 更新总体匹配结果
//                allMatch = allMatch && detailsMatch;
//                match.setMatchResult(allMatch ? "匹配" : "不匹配");
//
//                // 如果明细不匹配，添加到差异信息
//                if (!detailsMatch) {
//                    difference.append("明细不一致: ");
//                    difference.append(detailsInfo);
//                    log.info("明细匹配失败，详细信息: {}", detailsInfo.toString());
//                }
//            }
//
//            // 设置差异信息和时间
//            match.setDifference(difference.toString());
//            match.setCreateTime(LocalDateTime.now());
//            match.setUpdateTime(LocalDateTime.now());
//            match.setMatchTime(LocalDateTime.now());
//
//            // 保存匹配记录
//            matchMapper.insert(match);
//            log.info("三单匹配完成, 结果: {}", match.getMatchResult());
//
//            // 如果匹配成功，则更新发票表中的订单ID和收货单ID
//            if (allMatch) {
//                log.info("三单匹配成功，更新发票关联信息，发票ID: {}, 订单ID: {}, 收货单ID: {}",
//                        invoice.getId(), order.getId(), receipt.getId());
//
//                // 设置发票的订单ID和收货单ID
//                Invoice invoiceToUpdate = new Invoice();
//                invoiceToUpdate.setId(invoice.getId());
//                invoiceToUpdate.setOrderId(order.getId());
//                invoiceToUpdate.setReceiptId(receipt.getId());
//
//                // 更新发票信息
//                invoiceService.update(invoiceToUpdate);
//                log.info("发票关联信息更新成功");
//            } else {
//                log.info("三单匹配不成功，不更新发票关联信息");
//            }
//
//            log.info("三单匹配完成：订单编号={}, 收货单编号={}, 发票编号={}, 匹配结果={}, 匹配时间={}",
//                    order.getOrderNumber(), receipt.getReceiptNumber(), invoice.getInvoiceNumber(),
//                    allMatch ? "匹配" : "不匹配", match.getMatchTime());
//
//            return Result.success(match);
//        } catch (BusinessException e) {
//            throw e;
//        } catch (Exception e) {
//            log.error("三单匹配失败", e);
//            throw new BusinessException("三单匹配执行失败: " + e.getMessage(), e);
//        }
//    }

    /**
     * 实现countTotal方法
     *
     * @return 总数
     */
    @Override
    public int countTotal() {
        return matchMapper.countTotal();
    }

//    /**
//     * 实现countByMatchResult方法
//     *
//     * @return 按匹配结果分组统计
//     */
//    @Override
//    public List<Map<String, Object>> countByMatchResult() {
//        return matchMapper.countByMatchResult();
//    }
//
//    /**
//     * 实现countMatchRateBySupplier方法
//     *
//     * @return 按供应商统计匹配准确率
//     */
//    @Override
//    public List<Map<String, Object>> countMatchRateBySupplier() {
//        return matchMapper.countMatchRateBySupplier();
//    }
//
//    /**
//     * 实现countMatchTrendByMonth方法
//     *
//     * @return 按月统计匹配趋势
//     */
//    @Override
//    public List<Map<String, Object>> countMatchTrendByMonth() {
//        return matchMapper.countMatchTrendByMonth();
//    }

    @Override
    public MatchStatisticsData getMatchStatistics(MatchQueryDTO params) {
        // 实现统计数据获取逻辑
        MatchStatisticsData data = new MatchStatisticsData();

        try {
            log.info("开始获取匹配统计数据，参数: {}", params);

            // 添加年份日志
            int year;
            if (params != null && params.getStartDate() != null) {
                year = params.getStartDate().getYear();
                log.info("从startDate中获取年份: {}", year);
            } else {
                year = LocalDate.now().getYear();
                log.info("未提供startDate，使用当前年份: {}", year);
            }

            // 获取匹配总数
            int totalMatches = matchMapper.countTotal();
            log.info("匹配总数: {}", totalMatches);

            // 设置概览数据
            Map<String, Object> overview = new HashMap<>();
            overview.put("totalMatches", totalMatches);

            // 获取按匹配结果分组的统计数据
            List<Map<String, Object>> resultStats = matchMapper.countByMatchResult();
            log.info("匹配结果分组统计: {}", resultStats);

            // 设置各种匹配状态的数量
            int successMatches = 0;
            int partialMatches = 0;
            int pendingMatches = 0;
            int exceptionMatches = 0;

            for (Map<String, Object> stat : resultStats) {
                String matchResult = (String) stat.get("matchResult");
                int count = ((Number) stat.get("count")).intValue();

                if ("匹配".equals(matchResult)) {
                    successMatches = count;
                } else if ("部分匹配".equals(matchResult)) {
                    partialMatches = count;
                } else if ("待匹配".equals(matchResult)) {
                    pendingMatches = count;
                } else if ("不匹配".equals(matchResult)) {
                    exceptionMatches = count;
                }
            }

            overview.put("successMatches", successMatches);
            overview.put("partialMatches", partialMatches);
            overview.put("pendingMatches", pendingMatches);
            overview.put("exceptionMatches", exceptionMatches);

            // 计算成功率
            String successRate = totalMatches > 0 ? String.format("%.1f%%", ((double) successMatches / totalMatches) * 100) : "0%";
            overview.put("successRate", successRate);

            data.setOverview(overview);

            // 设置状态分布
            data.setStatusDistribution(resultStats);

            // 获取匹配趋势 - 从数据库获取月度趋势数据
            List<Map<String, Object>> monthlyTrends = matchMapper.countMatchTrendByMonth();
            log.info("原始月度趋势数据: {}", monthlyTrends);

            // 如果有日期范围参数，筛选相应年份的数据
            if (params != null && params.getStartDate() != null) {
                log.info("按年份筛选月度趋势数据，年份: {}", year);

                // 创建完整的12个月数据
                List<Map<String, Object>> completeMonthlyTrends = generateCompleteMonthlyTrend(monthlyTrends, year);
                log.info("生成完整12个月数据: {}", completeMonthlyTrends);
                data.setMonthlyTrend(completeMonthlyTrends);
            } else {
                // 如果没有指定年份，使用当前年份
                log.info("未指定年份，使用当前年份: {}", year);

                // 创建完整的12个月数据
                List<Map<String, Object>> completeMonthlyTrends = generateCompleteMonthlyTrend(monthlyTrends, year);
                log.info("生成完整12个月数据: {}", completeMonthlyTrends);
                data.setMonthlyTrend(completeMonthlyTrends);
            }

            log.info("匹配统计数据获取成功");
            return data;
        } catch (Exception e) {
            log.error("获取匹配统计数据失败", e);
            // 返回空数据而不是抛出异常，避免前端崩溃
            return data;
        }
    }

    /**
     * 生成完整的12个月趋势数据
     *
     * @param monthlyTrends 原始月度趋势数据
     * @param year          年份
     * @return 完整的12个月数据
     */
    private List<Map<String, Object>> generateCompleteMonthlyTrend(List<Map<String, Object>> monthlyTrends, int year) {
        // 创建一个月份Map，用于存储已有的月度数据
        Map<String, Map<String, Object>> monthMap = new HashMap<>();

        // 将原始数据放入Map中
        for (Map<String, Object> trend : monthlyTrends) {
            String date = (String) trend.get("date");
            // 如果日期格式是yyyy-MM-dd，需要截取前7位
            if (date != null && date.length() > 7) {
                date = date.substring(0, 7);
            }

            // 检查是否是当前年份的数据
            if (date != null && date.startsWith(String.valueOf(year))) {
                String month = date.substring(5, 7); // 获取月份部分，例如"01"
                monthMap.put(month, trend);
            }
        }

        // 创建完整的12个月数据
        List<Map<String, Object>> completeMonthlyTrends = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            String month = i < 10 ? "0" + i : String.valueOf(i);
            String dateStr = year + "-" + month;

            if (monthMap.containsKey(month)) {
                // 使用已有数据
                Map<String, Object> existingData = new HashMap<>(monthMap.get(month));
                // 确保date字段的格式为yyyy-MM
                existingData.put("date", dateStr);

                // 确保所有必要字段都存在
                ensureField(existingData, "total", 0);
                ensureField(existingData, "success", 0);
                ensureField(existingData, "partial", 0);
                ensureField(existingData, "pending", 0);
                ensureField(existingData, "exception", 0);

                completeMonthlyTrends.add(existingData);
                log.debug("月份[{}]使用现有数据: {}", month, existingData);
            } else {
                // 创建空数据
                Map<String, Object> emptyData = new HashMap<>();
                emptyData.put("date", dateStr);
                emptyData.put("total", 0);
                emptyData.put("success", 0);
                emptyData.put("partial", 0);
                emptyData.put("pending", 0);
                emptyData.put("exception", 0);
                completeMonthlyTrends.add(emptyData);
                log.debug("月份[{}]创建空数据: {}", month, emptyData);
            }
        }

        return completeMonthlyTrends;
    }

    /**
     * 确保Map中存在指定字段，如果不存在则设置默认值
     */
    private void ensureField(Map<String, Object> map, String field, Object defaultValue) {
        if (!map.containsKey(field) || map.get(field) == null) {
            map.put(field, defaultValue);
        }
    }

    @Override
    public List<MatchResult> performGlobalMatch() {
        log.info("开始执行全局自动匹配");
        List<MatchResult> results = new ArrayList<>();

        try {
            // 1. 获取未匹配的发票列表 - 增加处理数量限制
            List<Invoice> unmatchedInvoices = invoiceService.findUnmatchedInvoices(500); // 每次最多处理500条未匹配的发票
            log.info("找到{}个未匹配的发票", unmatchedInvoices.size());

            if (unmatchedInvoices.isEmpty()) {
                log.info("没有找到未匹配的发票，匹配流程结束");
                return results;
            }

            // 2. 处理每个未匹配的发票
            for (Invoice invoice : unmatchedInvoices) {
                try {
                    // 判断发票基本信息是否完整
                    if (invoice.getSupplierName() == null || invoice.getTotalAmount() == null) {
                        log.warn("发票{}信息不完整，跳过匹配", invoice.getInvoiceNumber());
                        continue;
                    }

                    log.info("处理发票: ID={}, 编号={}, 供应商={}, 金额={}",
                            invoice.getId(), invoice.getInvoiceNumber(), invoice.getSupplierName(), invoice.getTotalAmount());

                    // 根据发票的供应商名称和金额寻找匹配的订单和收货单
                    String supplierName = invoice.getSupplierName();
                    BigDecimal totalAmount = invoice.getTotalAmount();

                    // 设置匹配金额的容差范围为正负10%（放宽容差以提高匹配率）
                    BigDecimal minAmount = totalAmount.multiply(new BigDecimal("0.90"));
                    BigDecimal maxAmount = totalAmount.multiply(new BigDecimal("1.10"));

                    log.info("查询匹配条件: 供应商={}, 金额范围={} - {}", supplierName, minAmount, maxAmount);

                    // 查找可能匹配的订单
                    List<Order> possibleOrders = orderService.findBySupplierAndAmount(
                            supplierName, totalAmount, minAmount, maxAmount);
                    log.info("找到{}个可能匹配的订单", possibleOrders.size());

                    // 如果未找到订单，尝试通过近似的供应商名称查找
                    if (possibleOrders.isEmpty()) {
                        log.info("尝试使用模糊匹配供应商名称查找订单");
                        possibleOrders = orderService.findBySimilarSupplierAndAmount(
                                supplierName, totalAmount, minAmount, maxAmount);
                        log.info("通过模糊匹配供应商找到{}个可能的订单", possibleOrders.size());
                    }

                    if (!possibleOrders.isEmpty()) {
                        for (Order order : possibleOrders) {
                            log.info("可能的订单: ID={}, 编号={}, 供应商={}, 金额={}",
                                    order.getId(), order.getOrderNumber(), order.getSupplierName(), order.getTotalAmount());
                        }
                    }

                    // 查找可能匹配的收货单
                    List<Receipt> possibleReceipts = receiptService.findBySupplierAndAmount(
                            supplierName, totalAmount, minAmount, maxAmount);
                    log.info("找到{}个可能匹配的收货单", possibleReceipts.size());

                    // 如果未找到收货单，尝试通过近似的供应商名称查找
                    if (possibleReceipts.isEmpty()) {
                        log.info("尝试使用模糊匹配供应商名称查找收货单");
                        possibleReceipts = receiptService.findBySimilarSupplierAndAmount(
                                supplierName, totalAmount, minAmount, maxAmount);
                        log.info("通过模糊匹配供应商找到{}个可能的收货单", possibleReceipts.size());
                    }

                    if (!possibleReceipts.isEmpty()) {
                        for (Receipt receipt : possibleReceipts) {
                            log.info("可能的收货单: ID={}, 编号={}, 供应商={}, 金额={}",
                                    receipt.getId(), receipt.getReceiptNumber(), receipt.getSupplierName(), receipt.getTotalAmount());
                        }
                    }

                    // 如果找到可能的订单和收货单，尝试匹配
                    if (!possibleOrders.isEmpty() && !possibleReceipts.isEmpty()) {
                        // 优先匹配相同订单号的订单和收货单
                        Order bestMatchOrder = null;
                        Receipt bestMatchReceipt = null;

                        // 查找最佳匹配的订单和收货单
                        for (Order order : possibleOrders) {
                            for (Receipt receipt : possibleReceipts) {
                                if (receipt.getOrderId() != null && receipt.getOrderId().equals(order.getId())) {
                                    bestMatchOrder = order;
                                    bestMatchReceipt = receipt;
                                    log.info("找到最佳匹配：订单ID={}与收货单ID={}关联", order.getId(), receipt.getId());
                                    break;
                                }
                            }
                            if (bestMatchOrder != null) break;
                        }

                        // 如果没有找到关联的订单和收货单，选择金额最接近的组合
                        if (bestMatchOrder == null) {
                            // 寻找金额最接近的订单
                            Order closestOrder = findClosestAmountOrder(possibleOrders, totalAmount);
                            log.info("选择金额最接近的订单: ID={}, 金额差额={}",
                                    closestOrder.getId(),
                                    closestOrder.getTotalAmount().subtract(totalAmount).abs());

                            // 在可能的收货单中查找与选择订单关联的收货单
                            for (Receipt receipt : possibleReceipts) {
                                if (receipt.getOrderId() != null && receipt.getOrderId().equals(closestOrder.getId())) {
                                    bestMatchOrder = closestOrder;
                                    bestMatchReceipt = receipt;
                                    log.info("找到与选择订单关联的收货单: ID={}", receipt.getId());
                                    break;
                                }
                            }

                            // 如果仍然没有找到，选择金额最接近的收货单
                            if (bestMatchReceipt == null) {
                                Receipt closestReceipt = findClosestAmountReceipt(possibleReceipts, totalAmount);
                                bestMatchOrder = closestOrder;
                                bestMatchReceipt = closestReceipt;
                                log.info("选择金额最接近的收货单: ID={}, 金额差额={}",
                                        closestReceipt.getId(),
                                        closestReceipt.getTotalAmount().subtract(totalAmount).abs());
                            }
                        }

                        // 执行三单匹配
                        log.info("执行三单匹配: 订单ID={}, 收货单ID={}, 发票ID={}",
                                bestMatchOrder.getId(), bestMatchReceipt.getId(), invoice.getId());

                        MatchResult result = matchThreeDocuments(
                                bestMatchOrder.getId(), bestMatchReceipt.getId(), invoice.getId());

                        if (result != null) {
                            results.add(result);
                            log.info("成功匹配三单: 订单号={}, 收货单号={}, 发票号={}, 匹配结果={}",
                                    bestMatchOrder.getOrderNumber(),
                                    bestMatchReceipt.getReceiptNumber(),
                                    invoice.getInvoiceNumber(),
                                    result.isMatch() ? "匹配" : "不匹配");
                        } else {
                            log.warn("三单匹配返回结果为null");
                        }
                    } else if (!possibleOrders.isEmpty()) {
                        log.info("只找到匹配订单，但没有找到匹配的收货单");
                        // 选择最匹配的订单，创建一个匹配结果以显示在UI中
                        Order bestOrder = findClosestAmountOrder(possibleOrders, totalAmount);

                        // 创建匹配结果
                        MatchResult partialResult = new MatchResult();
                        partialResult.setMatch(false);
                        partialResult.setOrderInfo(bestOrder);
                        partialResult.setInvoiceInfo(invoice);
                        partialResult.setOrderNumber(bestOrder.getOrderNumber());
                        partialResult.setInvoiceNumber(invoice.getInvoiceNumber());
                        // 确保receiptNumber不为null
                        partialResult.setReceiptNumber("暂无");
                        partialResult.setSupplierName(bestOrder.getSupplierName() != null ? bestOrder.getSupplierName() : invoice.getSupplierName());
                        partialResult.setReason("找到匹配订单，但缺少匹配的收货单");
                        partialResult.setMatchTime(LocalDateTime.now());

                        // 创建字段级匹配信息，包含金额
                        List<MatchField> fields = new ArrayList<>();

                        // 添加金额匹配字段
                        MatchField amountField = new MatchField();
                        amountField.setFieldName("金额");
                        amountField.setOrderValue(bestOrder.getTotalAmount().toString());
                        amountField.setInvoiceValue(invoice.getTotalAmount().toString());
                        amountField.setReceiptValue("未知");
                        amountField.setMatch(false);
                        fields.add(amountField);

                        partialResult.setFields(fields);

                        results.add(partialResult);
                        log.info("创建了部分匹配结果: 订单号={}, 发票号={}, 匹配结果=不匹配, 原因={}",
                                bestOrder.getOrderNumber(), invoice.getInvoiceNumber(), partialResult.getReason());
                    } else if (!possibleReceipts.isEmpty()) {
                        log.info("只找到匹配收货单，但没有找到匹配的订单");
                        // 从收货单查找关联的订单
                        Receipt bestReceipt = findClosestAmountReceipt(possibleReceipts, totalAmount);
                        Order relatedOrder = null;

                        if (bestReceipt.getOrderId() != null) {
                            relatedOrder = orderService.findById(bestReceipt.getOrderId());
                            if (relatedOrder != null) {
                                log.info("通过收货单关联找到订单: ID={}", relatedOrder.getId());

                                // 执行三单匹配
                                MatchResult result = matchThreeDocuments(
                                        relatedOrder.getId(), bestReceipt.getId(), invoice.getId());

                                if (result != null) {
                                    results.add(result);
                                    log.info("成功匹配三单: 订单号={}, 收货单号={}, 发票号={}, 匹配结果={}",
                                            relatedOrder.getOrderNumber(),
                                            bestReceipt.getReceiptNumber(),
                                            invoice.getInvoiceNumber(),
                                            result.isMatch() ? "匹配" : "不匹配");
                                }
                            } else {
                                // 关联订单不存在，创建部分匹配结果
                                MatchResult partialResult = new MatchResult();
                                partialResult.setMatch(false);
                                partialResult.setReceiptInfo(bestReceipt);
                                partialResult.setInvoiceInfo(invoice);
                                partialResult.setReceiptNumber(bestReceipt.getReceiptNumber());
                                partialResult.setInvoiceNumber(invoice.getInvoiceNumber());
                                // 确保orderNumber不为null
                                partialResult.setOrderNumber("暂无");
                                partialResult.setSupplierName(bestReceipt.getSupplierName() != null ? bestReceipt.getSupplierName() : invoice.getSupplierName());
                                partialResult.setReason("找到匹配收货单，但关联订单不存在");
                                partialResult.setMatchTime(LocalDateTime.now());

                                // 创建字段级匹配信息，包含金额
                                List<MatchField> fields = new ArrayList<>();

                                // 添加金额匹配字段
                                MatchField amountField = new MatchField();
                                amountField.setFieldName("金额");
                                amountField.setOrderValue("未知");
                                amountField.setReceiptValue(bestReceipt.getTotalAmount().toString());
                                amountField.setInvoiceValue(invoice.getTotalAmount().toString());
                                amountField.setMatch(false);
                                fields.add(amountField);

                                partialResult.setFields(fields);

                                results.add(partialResult);
                                log.info("创建了部分匹配结果: 收货单号={}, 发票号={}, 匹配结果=不匹配, 原因={}",
                                        bestReceipt.getReceiptNumber(), invoice.getInvoiceNumber(), partialResult.getReason());
                            }
                        } else {
                            // 收货单没有关联订单，创建部分匹配结果
                            MatchResult partialResult = new MatchResult();
                            partialResult.setMatch(false);
                            partialResult.setReceiptInfo(bestReceipt);
                            partialResult.setInvoiceInfo(invoice);
                            partialResult.setReceiptNumber(bestReceipt.getReceiptNumber());
                            partialResult.setInvoiceNumber(invoice.getInvoiceNumber());
                            // 确保orderNumber不为null
                            partialResult.setOrderNumber("暂无");
                            partialResult.setSupplierName(bestReceipt.getSupplierName() != null ? bestReceipt.getSupplierName() : invoice.getSupplierName());
                            partialResult.setReason("找到匹配收货单，但没有关联订单");
                            partialResult.setMatchTime(LocalDateTime.now());

                            // 创建字段级匹配信息，包含金额
                            List<MatchField> fields = new ArrayList<>();

                            // 添加金额匹配字段
                            MatchField amountField = new MatchField();
                            amountField.setFieldName("金额");
                            amountField.setOrderValue("未知");
                            amountField.setReceiptValue(bestReceipt.getTotalAmount().toString());
                            amountField.setInvoiceValue(invoice.getTotalAmount().toString());
                            amountField.setMatch(false);
                            fields.add(amountField);

                            partialResult.setFields(fields);

                            results.add(partialResult);
                            log.info("创建了部分匹配结果: 收货单号={}, 发票号={}, 匹配结果=不匹配, 原因={}",
                                    bestReceipt.getReceiptNumber(), invoice.getInvoiceNumber(), partialResult.getReason());
                        }
                    } else {
                        log.info("发票{}没有找到匹配的订单或收货单", invoice.getInvoiceNumber());

                        // 即使没有匹配上，也创建匹配结果，以便在UI中显示
                        MatchResult noMatchResult = new MatchResult();
                        noMatchResult.setMatch(false);
                        noMatchResult.setInvoiceInfo(invoice);
                        noMatchResult.setInvoiceNumber(invoice.getInvoiceNumber());
                        // 设置订单编号和收货单编号为"暂无"而不是空字符串
                        noMatchResult.setOrderNumber("暂无");
                        noMatchResult.setReceiptNumber("暂无");
                        noMatchResult.setSupplierName(invoice.getSupplierName());
                        noMatchResult.setReason("未找到匹配的订单和收货单");
                        noMatchResult.setMatchTime(LocalDateTime.now());

                        // 创建字段级匹配信息，包含金额
                        List<MatchField> fields = new ArrayList<>();

                        // 添加金额匹配字段
                        MatchField amountField = new MatchField();
                        amountField.setFieldName("金额");
                        amountField.setOrderValue("未知");
                        amountField.setReceiptValue("未知");
                        amountField.setInvoiceValue(invoice.getTotalAmount().toString());
                        amountField.setMatch(false);
                        fields.add(amountField);

                        noMatchResult.setFields(fields);

                        results.add(noMatchResult);
                        log.info("创建了不匹配结果: 发票号={}, 订单号={}, 收货单号={}, 匹配结果=不匹配, 原因={}",
                                invoice.getInvoiceNumber(), noMatchResult.getOrderNumber(), noMatchResult.getReceiptNumber(), noMatchResult.getReason());
                    }
                } catch (Exception e) {
                    // 单个发票的异常不应该影响整个匹配过程
                    log.error("处理发票{}时发生错误: {}", invoice.getInvoiceNumber(), e.getMessage(), e);
                }
            }

            log.info("全局自动匹配完成，共匹配成功{}单", results.size());
            return results;
        } catch (Exception e) {
            log.error("全局自动匹配过程中发生错误: {}", e.getMessage(), e);
            throw new BusinessException("全局自动匹配失败: " + e.getMessage(), e);
        }
    }

    /**
     * 查找金额最接近的订单
     *
     * @param orders       订单列表
     * @param targetAmount 目标金额
     * @return 金额最接近的订单
     */
    private Order findClosestAmountOrder(List<Order> orders, BigDecimal targetAmount) {
        Order closestOrder = orders.get(0);
        BigDecimal minDiff = closestOrder.getTotalAmount().subtract(targetAmount).abs();

        for (Order order : orders) {
            BigDecimal diff = order.getTotalAmount().subtract(targetAmount).abs();
            if (diff.compareTo(minDiff) < 0) {
                minDiff = diff;
                closestOrder = order;
            }
        }

        return closestOrder;
    }

    /**
     * 查找金额最接近的收货单
     *
     * @param receipts     收货单列表
     * @param targetAmount 目标金额
     * @return 金额最接近的收货单
     */
    private Receipt findClosestAmountReceipt(List<Receipt> receipts, BigDecimal targetAmount) {
        Receipt closestReceipt = receipts.get(0);
        BigDecimal minDiff = closestReceipt.getTotalAmount().subtract(targetAmount).abs();

        for (Receipt receipt : receipts) {
            BigDecimal diff = receipt.getTotalAmount().subtract(targetAmount).abs();
            if (diff.compareTo(minDiff) < 0) {
                minDiff = diff;
                closestReceipt = receipt;
            }
        }

        return closestReceipt;
    }

    /**
     * 获取可三单匹配的订单列表
     */
    @Override
    public PageResult<Order> getOrdersAvailableForMatch(int pageNum, int pageSize, String supplierName,
                                                        String orderNumber, String startDate, String endDate) {
        log.info("获取可三单匹配的订单列表, 页码: {}, 每页大小: {}, 供应商: {}, 订单编号: {}, 日期范围: {} - {}",
                pageNum, pageSize, supplierName, orderNumber, startDate, endDate);
        try {
            // 验证分页参数
            if (pageNum <= 0) {
                pageNum = 1;
                log.warn("页码参数无效，已设置为默认值1");
            }

            if (pageSize <= 0 || pageSize > 100) {
                pageSize = 10;
                log.warn("每页大小参数无效，已设置为默认值10");
            }

            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("offset", offset);
            params.put("pageSize", pageSize);

            if (supplierName != null && !supplierName.isEmpty()) {
                params.put("supplierName", supplierName);
            }

            if (orderNumber != null && !orderNumber.isEmpty()) {
                params.put("orderNumber", orderNumber);
            }

            if (startDate != null && !startDate.isEmpty()) {
                params.put("startDate", startDate);
            }

            if (endDate != null && !endDate.isEmpty()) {
                params.put("endDate", endDate);
            }

            // 查询可匹配的订单总数
            int total = matchMapper.countOrdersAvailableForMatch(params);

            // 查询可匹配的订单列表
            List<Order> orders = matchMapper.findOrdersAvailableForMatch(params);

            // 构建分页结果
            return PageResult.of((long) total, orders, pageSize, pageNum);
        } catch (Exception e) {
            log.error("获取可三单匹配的订单列表失败", e);
            throw new BusinessException("获取可三单匹配的订单列表失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取已完成三单匹配的订单列表
     */
    @Override
    public PageResult<MatchedOrderVO> getMatchedOrders(int pageNum, int pageSize, String supplierName,
                                                       String orderNumber, String matchResult, String startDate, String endDate) {
        log.info("获取已完成三单匹配的订单列表, 页码: {}, 每页大小: {}, 供应商: {}, 订单编号: {}, 匹配结果: {}, 日期范围: {} - {}",
                pageNum, pageSize, supplierName, orderNumber, matchResult, startDate, endDate);
        try {
            // 验证分页参数
            if (pageNum <= 0) {
                pageNum = 1;
                log.warn("页码参数无效，已设置为默认值1");
            }

            if (pageSize <= 0 || pageSize > 100) {
                pageSize = 10;
                log.warn("每页大小参数无效，已设置为默认值10");
            }

            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("offset", offset);
            params.put("pageSize", pageSize);

            if (supplierName != null && !supplierName.isEmpty()) {
                params.put("supplierName", supplierName);
            }

            if (orderNumber != null && !orderNumber.isEmpty()) {
                params.put("orderNumber", orderNumber);
            }

            if (matchResult != null && !matchResult.isEmpty()) {
                params.put("matchResult", matchResult);
            }

            if (startDate != null && !startDate.isEmpty()) {
                params.put("startDate", startDate);
            }

            if (endDate != null && !endDate.isEmpty()) {
                params.put("endDate", endDate);
            }

            // 查询已匹配的订单总数
            int total = matchMapper.countMatchedOrders(params);

            // 查询已匹配的订单列表
            List<MatchedOrderVO> matchedOrders = matchMapper.findMatchedOrders(params);

            // 构建分页结果
            return PageResult.of((long) total, matchedOrders, pageSize, pageNum);
        } catch (Exception e) {
            log.error("获取已完成三单匹配的订单列表失败", e);
            throw new BusinessException("获取已完成三单匹配的订单列表失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取可与指定订单匹配的收货单列表
     */
    @Override
    public List<Receipt> getReceiptsForOrderMatch(Long orderId) {
        log.info("获取可与订单ID={}匹配的收货单列表", orderId);
        try {
            if (orderId == null) {
                throw new IllegalArgumentException("订单ID不能为空");
            }

            // 根据订单ID查询可匹配的收货单
            List<Receipt> receipts = matchMapper.findReceiptsForOrderMatch(orderId);
            log.info("找到{}个可匹配的收货单", receipts.size());

            return receipts;
        } catch (Exception e) {
            log.error("获取可匹配收货单列表失败", e);
            throw new BusinessException("获取可匹配收货单列表失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取可与指定订单匹配的发票列表
     */
    @Override
    public List<Invoice> getInvoicesForOrderMatch(Long orderId) {
        log.info("获取可与订单ID={}匹配的发票列表", orderId);
        try {
            if (orderId == null) {
                throw new IllegalArgumentException("订单ID不能为空");
            }

            // 根据订单ID查询可匹配的发票
            List<Invoice> invoices = matchMapper.findInvoicesForOrderMatch(orderId);
            log.info("找到{}个可匹配的发票", invoices.size());

            return invoices;
        } catch (Exception e) {
            log.error("获取可匹配发票列表失败", e);
            throw new BusinessException("获取可匹配发票列表失败: " + e.getMessage(), e);
        }
    }

    /**
     * 批量删除匹配记录
     *
     * @param ids 匹配记录ID列表
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public boolean batchDelete(List<Long> ids) {
        log.info("批量删除匹配记录, IDs: {}", ids);
        try {
            if (ids == null || ids.isEmpty()) {
                log.warn("匹配记录ID列表为空，无需删除");
                return true;
            }

            // 验证所有ID是否存在
            for (Long id : ids) {
                ThreeWayMatch match = matchMapper.findById(id);
                if (match == null) {
                    log.warn("匹配记录不存在, ID: {}", id);
                    return false;
                }
            }

            // 批量删除匹配记录
            int deletedCount = matchMapper.batchDelete(ids);
            log.info("成功删除{}条匹配记录", deletedCount);

            // 如果删除的记录数与ID列表长度不一致，说明部分删除失败
            return deletedCount == ids.size();
        } catch (Exception e) {
            log.error("批量删除匹配记录失败", e);
            throw new BusinessException("批量删除匹配记录失败: " + e.getMessage(), e);
        }
    }

    /**
     * 根据单号自动匹配
     *
     * @param orderCode   订单号
     * @param receiptCode 收货单号
     * @param invoiceCode 发票号
     * @return 匹配结果
     */
    @Override
    @Transactional
    public MatchResult autoMatchByCode(String orderCode, String receiptCode, String invoiceCode) {
        try {
            log.info("根据单号自动匹配, 订单号: {}, 收货单号: {}, 发票号: {}", orderCode, receiptCode, invoiceCode);

            // 参数校验
            if (StringUtils.isEmpty(orderCode) || StringUtils.isEmpty(receiptCode) || StringUtils.isEmpty(invoiceCode)) {
                log.warn("单号自动匹配参数不完整");
                return null;
            }

            // 根据单号查询单据
            Order order = orderService.findByOrderNumber(orderCode);
            Receipt receipt = receiptService.findByReceiptNumber(receiptCode);
            Invoice invoice = invoiceService.findByInvoiceNumber(invoiceCode);

            // 检查是否找到所有单据
            if (order == null || receipt == null || invoice == null) {
                log.warn("未找到对应的订单、收货单或发票数据");
                return null;
            }

            // 执行三单匹配
            return matchThreeDocuments(order.getId(), receipt.getId(), invoice.getId());
        } catch (Exception e) {
            log.error("根据单号自动匹配失败", e);
            return null;
        }
    }

    @Override
    public List<Order> getOrdersByInvoiceId(Long invoiceId) {
        if (invoiceId == null) {
            log.warn("获取关联订单时发票ID为空");
            return Collections.emptyList();
        }

        try {
            log.info("获取发票关联的订单, 发票ID: {}", invoiceId);

            // 从三单匹配表中查询关联的订单
            List<Order> orders = matchMapper.findOrdersByInvoiceId(invoiceId);

            if (orders != null && !orders.isEmpty()) {
                // 获取订单明细
                for (Order order : orders) {
                    if (order != null && order.getId() != null) {
                        List<OrderItem> items = orderService.getOrderItems(order.getId());
                        order.setItems(items);
                    }
                }

                log.info("找到发票关联的订单数量: {}", orders.size());
                return orders;
            }

            log.info("未找到发票关联的订单, 发票ID: {}", invoiceId);
            return Collections.emptyList();
        } catch (Exception e) {
            log.error("获取发票关联订单失败, 发票ID: {}", invoiceId, e);
            return Collections.emptyList();
        }
    }

    /**
     * 检查两组商品之间的双向兼容性
     *
     * @param group1 第一组商品
     * @param group2 第二组商品
     * @return 是否兼容
     */
    private boolean checkBidirectionalCompatibility(List<String> group1, List<String> group2) {
        // 检查group1中的每个商品是否可以由group2组成
        boolean group1CompatibleWithGroup2 = false;
        for (String item : group1) {
            if (aiService.checkItemsCompatibility(item, group2)) {
                group1CompatibleWithGroup2 = true;
                break;
            }
        }

        // 检查group2中的每个商品是否可以由group1组成
        boolean group2CompatibleWithGroup1 = false;
        for (String item : group2) {
            if (aiService.checkItemsCompatibility(item, group1)) {
                group2CompatibleWithGroup1 = true;
                break;
            }
        }

        // 只要有一个方向兼容，就认为两组商品兼容
        return group1CompatibleWithGroup2 || group2CompatibleWithGroup1;
    }
} 